package com.hr;

import java.util.Calendar;
import java.util.Date;

import com.espirit.eap.util.DateUtils;
import com.googlecode.cswish.exception.ApplicationException;

public class TimeRange {
	final public static String MARK_DUTY = "duty";//上班
	final public static String MARK_OT = "ot";//加班
	final public static String MARK_LEAVEAPP = "ot_exchange";//调休
	
	public TimeRange(Date timeFrom, Date timeTo) {
		setTimeFrom(timeFrom);
		setTimeTo(timeTo);
	}
	
	public TimeRange(Date date, int fromHour, int fromMinute, int toHour, int toMinute) {
		validateHour(fromHour);
		validateHour(toHour);
		validateMinute(fromMinute);
		validateMinute(toMinute);

		
		Calendar c = Calendar.getInstance();
		c.clear();
		c.setTime(date);
		
		c.set(Calendar.HOUR_OF_DAY, fromHour);
		c.set(Calendar.MINUTE, fromMinute);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		setTimeFrom(c.getTime());
		
		c.clear();
		c.setTime(date);
		if (toHour < fromHour) {//次日凌晨
			int day = c.get(Calendar.DAY_OF_MONTH);
			day++;
			c.set(Calendar.DAY_OF_MONTH, day);
		}
		c.set(Calendar.HOUR_OF_DAY, toHour);
		c.set(Calendar.MINUTE, toMinute);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		setTimeTo(c.getTime());
	}
	
	
	protected void setTimeFrom(Date timeFrom) {
		this.timeFrom = timeFrom;
		this.timeFromMinute = DateUtils.millsecond2Minute(this.timeFrom);
	}
	
	protected void setTimeTo(Date timeTo) {
		this.timeTo = timeTo;
		this.timeToMinute = DateUtils.millsecond2Minute(this.timeTo);
	}
	
	public boolean isIntersect(TimeRange timeRange) {
		boolean ret = false;
		
		long maxTimeFromMinute = Math.max(this.timeFromMinute, timeRange.timeFromMinute);
		long minTimeToMinute = Math.min(this.timeToMinute, timeRange.timeToMinute);
		
		if (minTimeToMinute > maxTimeFromMinute) {
			ret = true;
		}
		
		return ret;
	}
	
	
	public long getTimeFromMinute() {
		return timeFromMinute;
	}

	public long getTimeToMinute() {
		return timeToMinute;
	}

	public Date getTimeFrom() {
		return timeFrom;
	}

	public Date getTimeTo() {
		return timeTo;
	}

	public String getMark() {
		return mark;
	}

	public void setMarkAndType(String mark, Integer type) {
		this.mark = mark;
		this.type = type;
	}
	
	public Integer getType() {
		return type;
	}

	public int getTimeRangeMinute() {
		return (int)(this.timeToMinute - this.timeFromMinute);
	}

	private void validateHour(int hour) {
		if (hour > 23 || hour < 0) {
			throw new ApplicationException("invalid hour value range is 0-23");
		}
	}
	
	private void validateMinute(int minute) {
		if (minute > 59 || minute < 0) {
			throw new ApplicationException("invalid minute value range is 0-59");
		}
	}
	

	protected Date timeFrom;
	protected Date timeTo;
	protected long timeFromMinute;
	protected long timeToMinute;
	protected String mark;
	protected Integer type;
}
